package com.v2future.sjt.collegecheckingattendance.utils.netutils;

import android.text.TextUtils;

import com.v2future.sjt.collegecheckingattendance.MainActivity;
import com.v2future.sjt.collegecheckingattendance.utils.Constants;

import org.xutils.http.RequestParams;
import org.xutils.http.app.ParamsBuilder;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * Created by Administrator on 2016/2/1.
 */
public class BaseRequestParams extends RequestParams{

    MainActivity mActivity;

    public BaseRequestParams(String uri) {
        super(uri);
    }

    public BaseRequestParams(MainActivity activity, String uri){
        super(uri);
        mActivity = activity;
        init();
        setConnectTimeout(Constants.REQUEST_TIME);
    }

    public BaseRequestParams() {
        super();
    }

    public BaseRequestParams(String uri, ParamsBuilder builder, String[] signs, String[] cacheKeys) {
        super(uri, builder, signs, cacheKeys);
        setConnectTimeout(Constants.REQUEST_TIME);
    }

    /**
     * 添加默认的参数
     */
    public void init(){
        if (null == mActivity || null == mActivity.getUserInfo()) return;
        addQueryStringParameter("userCode", mActivity.getUserInfo().getData().getUserCode());
    }

    /**
     * 移除userCode字段
     */
    public void removeUserCode(){
        removeParameter("userCode");
    }

    @Override
    public void addQueryStringParameter(String name, String value) {
        if (!TextUtils.isEmpty(value)) {
            value = urlEncode(value);
        }
        if (null == value) return;
        super.addQueryStringParameter(name, value);
    }

    /**
     * url转码
     * @param str
     * @return
     */
    public String urlEncode(String str){
        String result = str;
        try {
            result = URLEncoder.encode(str, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }
}
